package com.yc.bank.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.yc.bank.biz.HelloBiz;
import com.yc.bank.entity.Account;
import com.yc.bank.entity.Result;
import com.yc.bank.mapper.AccountMapper;
import com.yc.bank.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Wrapper;
import java.util.List;

@WebServlet("/login.s")
public class LoginServlet extends HttpServlet {

    @Autowired
    HelloBiz helloBiz1;
    //@Resource
    HelloBiz helloBiz2;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("helloBiz1 = " + helloBiz1);
        System.out.println("helloBiz2 = " + helloBiz2);

        resp.setContentType("application/json;charset=utf-8");
        final WebApplicationContext ctx =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        final IAccountService accountService = ctx.getBean(IAccountService.class);
        final AccountMapper accountMapper = ctx.getBean(AccountMapper.class);

        final String name = req.getParameter("name");
        final String pwd = req.getParameter("pwd");

        // MyBatis-Plus 条件构建器
//        QueryWrapper<Account> qw = new QueryWrapper<>();
//        qw.eq("id", name); // id = ?
//        qw.eq("password", pwd);
        LambdaQueryWrapper<Account> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Account::getId, name);
        lqw.eq(Account::getPassword, pwd);
        final List<Account> list = accountMapper.selectList(lqw);
        Result result = null;
        try{
            Account account = accountService.getOne(lqw);
            if(account == null){
                result = new Result(0, "用户名或密码错误", null);
            } else {
                result = new Result(1, "登录成功!", null);
            }
        }catch (RuntimeException e){
            // 多个同名的记录 ==> 设计的问题
            e.printStackTrace();
        }

        final String j = new Gson().toJson(result);
        resp.getWriter().append(j);

    }

}
